package com.kingwang.training.designpattern.exam.service.impl;

import com.kingwang.training.designpattern.exam.bo.Task;
import com.kingwang.training.designpattern.exam.bo.TaskStatus;
import com.kingwang.training.designpattern.exam.bo.event.EventBus;
import com.kingwang.training.designpattern.exam.bo.event.TaskCreatedEvent;
import com.kingwang.training.designpattern.exam.dao.TaskDao;
import com.kingwang.training.designpattern.exam.dto.AddTaskDTO;
import com.kingwang.training.designpattern.exam.dto.AssignTaskDTO;
import com.kingwang.training.designpattern.exam.service.TaskService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author King
 */
@Service
public class TaskServiceImpl implements TaskService {
    @Resource
    private TaskDao taskDao;

    @Resource
    private EventBus eventBus;

    @Override
    public UUID addTask(AddTaskDTO dto) {
        Task entity = new Task();

        entity.setId(UUID.randomUUID());
        entity.setIssueType(dto.getIssueType());
        entity.setProductId(dto.getProductId());
        entity.setProductSerialNumber(dto.getProductSerialNumber());
        entity.setStatus(TaskStatus.NEW);
        entity.setCreateDateTime(LocalDateTime.now());
        entity.setCreatorId(dto.getCreatorId());

        UUID result = this.taskDao.addTask(entity);

        System.out.println("创建task成功");

        // 触发事件
        this.eventBus.publish(new TaskCreatedEvent(entity, LocalDateTime.now()));

        System.out.println("发布TaskCreatedEvent事件成功");

        return result;
    }

    @Override
    public void assignTask(AssignTaskDTO dto) {
        Task task = this.taskDao.getTaskById(dto.getTaskId());

        if (task == null) {
            return;
        }

        task.setWorkerId(dto.getWorkerId());
        task.setStatus(TaskStatus.ASSIGNED);

        this.taskDao.updateTask(task);
    }
}
